package com.zhkj.txg.module.order.ui

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.entity.node.BaseNode
import com.zhkj.lib.base.ViewModelActivity
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.RxBus
import com.zhkj.txg.R
import com.zhkj.txg.module.find.entity.FindPictureEntity
import com.zhkj.txg.module.order.adapter.OrderEvaluateAdapter
import com.zhkj.txg.module.order.entity.OrderListGoodsEntity
import com.zhkj.txg.module.order.vm.EvaluateUICommentEntity
import com.zhkj.txg.module.order.vm.EvaluateUIGoodsEntity
import com.zhkj.txg.module.order.vm.EvaluateViewModel
import com.zhkj.txg.utils.MatisseUtils
import com.zhihu.matisse.Matisse
import kotlinx.android.synthetic.main.activity_order_evaluate.*
import java.io.Serializable

@Suppress("UNCHECKED_CAST")
class OrderEvaluatePublishActivity : ViewModelActivity<EvaluateViewModel>() {

    companion object {
        private val ORDER_ID = "orderId"
        private val GOODS = "goods"
        private val ORDER_GROUP = "ORDER_GROUP"//拼团订单

        fun open(activity: Activity, orderId: Long, list: MutableList<OrderListGoodsEntity>, isGroup: Boolean = false) {
            val intent = Intent(activity, OrderEvaluatePublishActivity::class.java)
                .putExtra(ORDER_ID, orderId).putExtra(GOODS, list as Serializable)
            if (isGroup) {
                intent.putExtra(ORDER_GROUP, isGroup)
            }
            activity.startActivity(intent)
        }
    }

    var isGroup: Boolean = false
    override fun setViewModel(): EvaluateViewModel = createViewModel()
    override fun statusTitleBar(): View? = titleOrderEvaluate
    override val layoutResId: Int = R.layout.activity_order_evaluate

    private var requestCode: Int = 1000

    private val evaluateAdapter = OrderEvaluateAdapter({ uiPosition, realCount ->// 点击了添加图片按钮
        requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE, {
            requestCode = 1000 + uiPosition
            selectPicture(6 - realCount, requestCode)
        }, { toast(getString(R.string.read_permission_deny)) })
    }, { uiPosition, deletePosition -> // 点击了删除按钮
        viewModel.uiEntity.products[(uiPosition - 1) / 2].comment.imageList.removeAt(deletePosition)
        formatPictureData(uiPosition, mutableListOf())
    })

    override fun initUI() {
        with(rvOrderEvaluate) {
            (itemAnimator as? DefaultItemAnimator)?.supportsChangeAnimations = false
            layoutManager = LinearLayoutManager(this@OrderEvaluatePublishActivity)
            adapter = evaluateAdapter
        }
        tvOrderEvaluateConfirm.setOnClickListener {
            viewModel.uploadPicture(AccountManager.getToken(), intent.getLongExtra(ORDER_ID, 0), isGroup)
        }
    }

    override fun initViewModel() {
        isGroup = intent.getBooleanExtra(ORDER_GROUP, false)
        viewModel.submitEvaluateLiveData.observe(this, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip, true)
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.let {
                toast(it.msg ?: getString(R.string.evaluate_success))
                RxBus.post(OrderListRefreshEvent(listOf(Type.ALL, Type.COMPLETE)))
                finish()
            }
        })
    }

    override fun initData() {
        val list = intent.getSerializableExtra(GOODS) as List<OrderListGoodsEntity>
        // 构造UI数据
        viewModel.uiEntity.products.clear()
        list.forEach {
            viewModel.uiEntity.products.add(
                EvaluateUIGoodsEntity(
                    it.image, it.goodsName, it.specValue,
                    EvaluateUICommentEntity(goodsId = it.goodsId).apply {
                        // 添加按钮
                        imageList.add(FindPictureEntity())
                    }
                ).apply {
                    childNode = mutableListOf(comment)
                }
            )
        }
        evaluateAdapter.setNewData(viewModel.uiEntity.products as MutableList<BaseNode>)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK && requestCode == this.requestCode) {
            val uiPosition = requestCode - 1000
            // 构造已选照片参数，填充Adapter
            val selectPicList = Matisse.obtainPathResult(data)
            if (selectPicList.isNotEmpty()) {
                val list = mutableListOf<FindPictureEntity>()
                for (filePath in selectPicList) {
                    list.add(FindPictureEntity(filePath).apply {
                        itemType = FindPictureEntity.TYPE_PIC
                    })
                }
                formatPictureData(uiPosition, list)
            }
        }
    }

    /**
     * 打开图片选择器
     */
    private fun selectPicture(selectNum: Int, requestCode: Int) {
        MatisseUtils.selectPicture(this, requestCode, selectNum)
    }

    /**
     * 构造对应商品的图片数据
     */
    private fun formatPictureData(uiPosition: Int, list: MutableList<FindPictureEntity>) {
        with(viewModel.uiEntity.products[(uiPosition - 1) / 2].comment.imageList) {
            val filter = filter { it.itemType == FindPictureEntity.TYPE_PIC }
            clear()
            addAll(filter)
            addAll(list)
            if (size < 6) add(FindPictureEntity())
        }
        evaluateAdapter.notifyItemChanged(uiPosition)
    }
}